package com.faya.green.utils;

import com.faya.green.common.Constant;
import com.faya.green.model.CacheProcessor;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 用户：翔 创建时间： 2017/3/14.9:40
 * 地点：广州天河
 * 目的: 验证码 ,存放在session中的验证码 randomString
 */
public class VerifyCodeUtil {

    private static int width = 80;//图片的宽度
    private static int height = 30; //图片高
    private static int codeCount = 4; //验证码数
    private static int lineCount = 20; //干扰线数量
    private static String code = null; //验证码
    private static Random random = new Random();

    //生成图片
    public static void creatImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //字体的宽度
        int fontWidth = width / codeCount;
        //字体的高度
        int fontHeight = height - 5;
        int codeY = height - 8;

        BufferedImage bufferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferImage.getGraphics();
        //设置背景色
        g.setColor(getRandColor(200, 250));
        //填充矩形
        g.fillRect(0, 0, width, height);

        //设置字体 获得随机字体并设置
        g.setFont(getFont(fontHeight));

        // 设置干扰线
        for (int i = 0; i < lineCount; i++) {
            int xs = random.nextInt(width);
            int ys = random.nextInt(height);
            int xe = xs + random.nextInt(width);
            int ye = ys + random.nextInt(height);
            g.setColor(getRandColor(1, 255));
            g.drawLine(xs, ys, xe, ye);
        }

        // 添加噪点 噪声率
        float yawpRate = 0.01f;
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            bufferImage.setRGB(x, y, random.nextInt(255));
        }

        // 得到随机字符
        String str1 = randomStr(codeCount);
        code = str1;
        for (int i = 0;  i < codeCount; i ++){
            String strRand = str1.substring(i, i + 1);
            g.setColor(getRandColor(1, 255));
            g.drawString(strRand, i * fontWidth + 3, codeY);
        }

        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        //设置页面缓存的 防止JSP或者Servlet中的输出被浏览器保存在缓冲区中
        response.setDateHeader("Expires", 0);
        //getSession(true)若存在会话则返回该会话，否则新建一个会话.设值进入到session中
        HttpSession session = request.getSession(true);
        //存入该数据
        session.setAttribute(Constant.VERIFY_CODE, code);


        //转换成jpeg格式
        ////使用PrintWriter可能会带来一些小的开销，因为它将所有的原始输出都转换为字符流来输出，因此如果使用它来作为页面输出的话，系统要负担一个转换过程。而
        // 使用ServletOutputStream作为页面输出的话就不存在一个问题，但它是以二进制进行输出的.等价于PrintWriter
        ServletOutputStream sos = response.getOutputStream();
        //创建图片
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
        //将上面数据放入图中
        encoder.encode(bufferImage);
        //刷新
        sos.flush();
    }

    /**
     * 得到随机字符
     * @param n 验证码数
     * @return
     */
    private static String randomStr(int n) {
        //字体只显示大写，去掉了1,0,i,o几个容易混淆的字符
        String str1 = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        String str2 = "";
        int len = str1.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {
            r = (Math.random()) * len;
            str2 = str2 + str1.charAt((int) r);
        }
        return str2;
    }

    /**
     * 给定范围获得随机颜色
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandColor(int fc, int bc){
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 获得随机字体
     * @param size
     * @return
     */
    private static Font getFont(int size){
        Font font[] = new Font[5];
        font[0] = new Font("Ravie", Font.PLAIN, size);
        font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
        font[2] = new Font("Fixedsys", Font.PLAIN, size);
        font[3] = new Font("Wide Latin", Font.PLAIN, size);
        font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
        return font[random.nextInt(5)];
    }


}
